package dao;

import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JOptionPane;

import modelo.Item;
import modelo.Utiliza;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class DaoUtiliza {
	private static SessionFactory fabrica;

	public DaoUtiliza() throws Exception {
		fabrica = new Configuration().addClass(modelo.Utiliza.class).buildSessionFactory();
	}

	public static boolean cadastrarItem(ArrayList<Utiliza> listaItem) {
		try {
			
			for (Iterator<Utiliza> iterator = listaItem.iterator(); iterator.hasNext();) {
				Utiliza u = (Utiliza) iterator.next();
				
				Session sessao = fabrica.openSession();
				Transaction transacao = sessao.beginTransaction();
				sessao.save(u);
				transacao.commit();
				sessao.flush();
				sessao.close();
				
			}
			
			JOptionPane.showMessageDialog(null, "Salvou os Materiais");

			return true;
			
		} catch (Exception ex) {
			return false;
		}
	}

	public void excluir(Utiliza u) throws Exception {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();

		sessao.delete(u);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}

	public void alterar(Item b) throws Exception {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();

		sessao.update(b);
		transacao.commit();
		sessao.flush();
		sessao.close();
	}

	public ArrayList<Utiliza> consultarTodos() {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();
		Query q = sessao.createQuery("from modelo.Utiliza");
		ArrayList<Utiliza> Items = (ArrayList<Utiliza>) q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return Items;
	}

	public ArrayList<Utiliza> consultarUsaTipo(int idserv) {
		Session sessao = fabrica.openSession();
		Transaction transacao = sessao.beginTransaction();
		Query q = sessao.createQuery("from modelo.Utiliza where id_tipo_serv = " + idserv);
		ArrayList<Utiliza> usa = (ArrayList<Utiliza>) q.list();
		transacao.commit();
		sessao.flush();
		sessao.close();
		return usa;
	}
	

}
